<?php
namespace app\util;

class MeiliSearch {
    private $client;
    private $config;
    protected $currentIndex;

    public function __construct($config = []) {
        if(!$config){
            $config = config('meilisearch');
        }
        $this->config = $config;
        $this->client = new \MeiliSearch\Client($config['host'], $config['apiKey']);
    }

    public function createIndex($indexName, $primaryKey = 'id') {
        $this->currentIndex = $this->client->createIndex($indexName, ['primaryKey' => $primaryKey]);
        return $this;
    }

    public function setIndex($indexName){
        $this->currentIndex = $this->client->index($indexName);
        return $this;
    }

    public function addDocuments($documents) {
        $this->currentIndex->addDocuments($documents);
        return $this;
    }

    public function search($query, $options = []){
        $hits = $this->currentIndex->search($query, $options)->getHits();
        return $hits;
    }
}